import sys
import time
import subprocess
import pytest
from selenium import webdriver as web  # web 的 webdriver
from appium import webdriver as app   # appium 的webdriver

import os
root_dir = os.path.dirname(os.path.abspath(__file__))



def stop_appium(port):
    """
    停止appium
    :param port: 启动的端口号
    :return:
    """
    mac_cmd = f"lsof -i tcp:{port}"
    win_cmd = f"netstat -ano | findstr {port}"
    # 判断操作系统
    os_platform = sys.platform
    if os_platform == "win32":  #windows 系统
        win_p = subprocess.Popen(win_cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        for line in win_p.stdout.readlines():
            if line:
                line = line.decode('utf8')
                if "LISTENING" in line:
                    win_pid = line.split("LISTENING")[1].strip()
                    print(f"taskkill -f -pid {win_pid}")
                    os.system(f"taskkill -f -pid {win_pid}")
    else:                        # unix系统
        p = subprocess.Popen(mac_cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        for line in p.stdout.readlines():
            line = line.decode('utf8')
            # print("line",line)
            if "node" in line:
                stdoutline = line.split(" ")
                print(stdoutline)
                pid = stdoutline[4]
                os.system(f"kill {pid}")

def start_appium(port):
    """
    启动appium 服务
    :param port: 服务的端口号
    :return:
    """
    stop_appium(port)
    cmd = f"appium -p {port}"
    logsdir = os.path.join(os.path.dirname(os.path.abspath(__file__)),"logs")
    if not os.path.exists(logsdir):
        os.mkdir(logsdir)

    subprocess.Popen(cmd,shell=True, stdout=open('./logs/'+str(port)+".log",mode='a',encoding="utf8"),
                     stderr=subprocess.PIPE)


@pytest.fixture(scope="session")
def wdriver():

    # 定义浏览器的驱动
    driverpath = os.path.join(root_dir,'drivers/webchromedriver.exe')
    wdriver = web.Chrome(executable_path=driverpath)
    wdriver.implicitly_wait(5)
    wdriver.maximize_window()
    yield  wdriver
    # 所有的测试运行完毕之后 关闭 浏览器
    wdriver.quit()



@pytest.fixture(scope='session')
def adriver():
    # 定义 手机app driver
    start_appium(4723)
    chromedriver = os.path.join(root_dir,'drivers/appchromedriver.exe')
    desired_caps = {
        'platformName': 'Android',  # 测试Android系统
        'udid': "127.0.0.1:62001",  # adb devices 命令查看  设置为自己的设备
        'automationName': 'UiAutomator2',  # 自动化引擎
        'noReset': False,  # 不要重置app的状态
        'fullReset': False,  # 不要清理app的缓存数据
        'chromedriverExecutable': chromedriver,  # chromedriver 对应的绝对路径
        'appPackage': "org.cnodejs.android.md",  # 应用的包名
        'appActivity': ".ui.activity.LaunchActivity"  # 应用的活动页名称
    }

    adriver = app.Remote('http://127.0.0.1:4723/wd/hub', desired_capabilities=desired_caps)
    adriver.implicitly_wait(5)  # 全局的隐式等待时间

    yield adriver  # 将driver 传递出来
    # 所有的用例执行之后
    adriver.quit()
    stop_appium(4723)
